package com.atguigu.guli.service.sms.controller.api;

import com.aliyuncs.exceptions.ClientException;
import com.atguigu.guli.common.util.FormUtils;
import com.atguigu.guli.common.util.RandomUtils;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.sms.service.SmsService;
import com.atguigu.guli.service.sms.util.SmsProperties;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author Miluo
 * @description 短信管理
 **/
@RestController
@Api(tags = "短信管理")

@RequestMapping("/api/sms")
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R getCode(@PathVariable String mobile) throws ClientException {
        if (StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)){
            return R.error().message("手机号码有误");
        }

        //获取随机四位数验证码
        String code = RandomUtils.getFourBitRandom();

        //发送验证码
        smsService.send(mobile,code);

        //将验证码存入redis
        String key = "checkCode::" + mobile;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
